﻿using ProjBackEnd.Areas.Comprehensive.Models;
using ProjBackEnd.DAL;
using ProjBackEnd.Lib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;

namespace ProjBackEnd.Areas.Comprehensive.Controllers
{
    /// <summary>
    /// 归档文件操作
    /// </summary>
    public class ProfileManagementController : ApiController
    {
        /// <summary>
        /// 下载归档文件
        /// </summary>
        /// <param name="key">userid|公司代码|平台代码|归档文件流水号</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Comprehensive/DownloadArchiveFile")]
        public HttpResponseMessage DownloadArcFile(string key)
        {
            string strMemberid = "";
            try
            {
                string strToken = DataUtil.CheckTokenValid(Request);
                if (string.IsNullOrEmpty(strToken)) throw new Exception("非法请求");
                string[] strsRealKey = DataUtil.PlaintextConfusion(key, DataUtil.enumDeEncryptType.Decrypt).Split('|');
                if (strsRealKey.Length < 4) return new HttpResponseMessage(HttpStatusCode.BadRequest);
                strMemberid = strsRealKey[0];
                string strPlatcd = strsRealKey[2];
                int iFileid;
                if (!int.TryParse(strsRealKey[3], out iFileid)) throw new Exception("非法的归档文件流水号");
                if (!userLogic.CheckToken(strMemberid, strToken,strPlatcd)) throw new Exception("用户令牌无效");

                string strFilename = comprehensiveLogic.GetFileFullPathByDocid(iFileid);
                if(string.IsNullOrEmpty(strFilename)) return new HttpResponseMessage(HttpStatusCode.Gone);

                string strFilePath = GlobalSettings.FILEARCHIVEROOTPATH + strFilename;
                //strFilePath = @"D:\testdoc\bingov5.pdf";
                if (!File.Exists(strFilePath))
                {
                    return new HttpResponseMessage(HttpStatusCode.Gone);
                }

                FileStream stream = new FileStream(strFilePath, FileMode.Open);
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(stream) };
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = strFilename
                };
                return response;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message + ";" + strMemberid);
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }
        }

        /// <summary>
        /// 上传归档图片
        /// Header中包含【memberid:用户id;comcd:公司代码;platcd:平台代码;rule:归档规则名;key:归档关键字】
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Comprehensive/UploadArchiveFile")]
        public RespComprehensive UploadArcFile()
        {
            RespComprehensive resp = new RespComprehensive();
            string strToken = DataUtil.CheckTokenValid(Request);
            if (strToken == "")
            {
                resp.statusCode = 90002;
                resp.statusMsg = "非法请求";
                return resp;
            }

            if (!Request.Headers.Contains("memberid") || Request.Headers.GetValues("memberid") == null || !Request.Headers.Contains("rule") || Request.Headers.GetValues("rule") == null || !Request.Headers.Contains("key") || Request.Headers.GetValues("key") == null)
            {
                resp.statusCode = 90004;
                resp.statusMsg = "请求数据格式错误";
                return resp;
            }
            string strPlatcd = Request.Headers.GetValues("platcd").ToList()[0];
            string strComcd = Request.Headers.GetValues("comcd").ToList()[0];
            string strMemberid = Request.Headers.GetValues("memberid").ToList()[0];
            string strRule = Request.Headers.GetValues("rule").ToList()[0]; //归档规则名
            string strKey = Request.Headers.GetValues("key").ToList()[0]; //归档关键字
            if (!userLogic.CheckToken(strMemberid, strToken, strPlatcd))
            {
                resp.statusCode = 90001;
                resp.statusMsg = "用户令牌无效";
                return resp;
            }
            if (HttpContext.Current.Request.Files.Count == 0)
            {
                resp.statusCode = 90016;
                resp.statusMsg = "未找到要上传的文件。";
                return resp;
            }
            if (HttpContext.Current.Request.Files.Count > GlobalSettings.MAXUPLOADPICCOUNT)
            {
                resp.statusCode = 90016;
                resp.statusMsg = "图片单次上传最大数量超限。";
                return resp;
            }

            List<string> lst = comprehensiveLogic.FileArchiveCommon(strRule, strKey, HttpContext.Current.Request, strMemberid, strComcd);
            ResultUploadFileCommon res = new ResultUploadFileCommon { filereslist = lst };
            resp.result = res;
            if (lst.Count != HttpContext.Current.Request.Files.Count)
            {
                resp.statusCode = 90017;
                resp.statusMsg = "图片未能全部上传。成功：" + lst.Count.ToString() + "/" + HttpContext.Current.Request.Files.Count.ToString();
                return resp;
            }

            resp.statusCode = 0;
            resp.statusMsg = "图片上传成功";
            return resp;
        }

        /// <summary>
        /// 根据归档规则和归档关键字获取归档文件列表
        /// eg.:0000000001|TST|WEB|CT|6
        /// </summary>
        /// <param name="key">userid|公司代码|平台代码|归档规则名|归档关键字</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Comprehensive/ArcFileList")]
        public RespCompArcFile GetArcFileList(string key)
        {
            RespCompArcFile resp = new RespCompArcFile();
            if (string.IsNullOrEmpty(key))
            {
                resp.statusCode = 90004;
                resp.statusMsg = "请求数据格式错误";
                return resp;
            }

            string strToken = DataUtil.CheckTokenValid(Request);
            if (strToken == "")
            {
                resp.statusCode = 90002;
                resp.statusMsg = "非法请求";
                return resp;
            }

            string[] strsKeyOriginal = DataUtil.PlaintextConfusion(key, DataUtil.enumDeEncryptType.Decrypt).Split('|');
            if (strsKeyOriginal.Length < 5)
            {
                resp.statusCode = 90004;
                resp.statusMsg = "请求数据格式错误";
                return resp;
            }
            string strMemberid = strsKeyOriginal[0];
            string strComcd = strsKeyOriginal[1];
            string strPlatcd = strsKeyOriginal[2];
            string strRule = strsKeyOriginal[3];
            string strArcKey = strsKeyOriginal[4];

            resp = comprehensiveLogic.GetArcFileList(strComcd, strRule, strArcKey);
            return resp;
        }

        /// <summary>
        /// 删除归档文件
        /// </summary>
        /// <param name="_reqInfo">归档文件删除请求</param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Comprehensive/DeleteArchiveFile")]
        public RespCompNullResultInfo DelArchiveFile(ReqDelArcFile _reqInfo)
        {
            RespCompNullResultInfo resp = new RespCompNullResultInfo();
            if (!ModelState.IsValid)
            {
                string strErrmsg = DataUtil.GetModelStateError(ModelState);
                resp.statusCode = 90004;
                resp.statusMsg = "请求数据格式错误。" + strErrmsg;
                return resp;
            }

            string strToken = DataUtil.CheckTokenValid(Request);
            if (strToken == "")
            {
                resp.statusCode = 90002;
                resp.statusMsg = "非法请求";
                return resp;
            }

            if (!userLogic.CheckToken(_reqInfo.memberid, strToken, _reqInfo.platcd))
            {
                resp.statusCode = 90001;
                resp.statusMsg = "用户令牌无效";
                return resp;
            }

            resp = comprehensiveLogic.DelArcFile(_reqInfo.memberid, _reqInfo.comcd, _reqInfo.fileid);
            return resp;
        }

    }
}
